const express = require('express');
const { gql, ApolloServer } = require('apollo-server-express');
const mongoose = require('mongoose');
//1. 连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/user');
// 2.创建数据模型
const User = mongoose.model('User', {
    _id: String,
    username: String,
    password: String
})
//2.创建 schema
const types = gql`
    type User{
        _id:ID!,
        username:String,
        password:String
    }
    type Query{
        users:[User!]!
    }
`
//3.创建resolvers
const resolvers = {
    Query: {
        async users() {
            //查询数据库返回数据
            const res = await User.find();
            console.log(res)
            return res
        }
    }
}
// 5. 创建expr实例
const app = express();
//为何这样写 因为不这样写的话 会报错await server.start()` before calling `server.applyMiddleware()`
(async () => {
    // 6.创建 ApolloServer服务
    const server = new ApolloServer({ typeDefs: types, resolvers })
    await server.start();
    // 7.将exprees和ApolloServer混合
    server.applyMiddleware({ app })
    app.use((req, res) => {
        res.status(200).end('hhhhh')
    })
    app.listen(4000, () => {
        console.log('app is running')
    })

})()

